from app.core.http_client import HttpClient
from app.core.config import settings
from typing import List
from app.core.logger import logger

async def market_archive_page(
    page_no: int = 1,
    page_size: int = 50,
    xm_auth: str = ""
):
    """查询XM档案列表"""
    path = settings.XM_MARKET_ARCHIVE_PAGE
    req_body = {
        "pageNum": page_no,
        "pageSize": page_size,
        "timeType": 0,
        "dealCountSortType": False,
        "platformIdList": [],
        "communityIpIdList": [],
        "searchName": "",
        "topCode": ""
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    return response

async def get_archive_goods(
    archive_id: str,
    platform_id: int = 0,
    xm_auth: str = "",
    page_no: int = 1,
    page_size: int = 50
):
    """查询XM档案详情"""
    path = settings.XM_ARCHIVE_GOODS
    req_body = {
        "archiveId": archive_id,
        "platformId": platform_id,
        "pageNum": page_no,
        "pageSize": page_size,
        "source": "0",
        "sellStatus": 1,
        "dealType": 0,
        "goodsType": "",
        "isPayBond": "",
        "startTime": "",
        "endTime": ""
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'total': 51957, 'goodsMinPrice': 4.0, 'goodsArchiveList': [{'goodsId': 45777802, 'archiveId': 30684, 'goodsName': '黑白双色锦鲤', 'pfpImg': 'https://mdn.alipayobjects.com/chain_myent/afts/img/XyJTRIk3s80AAAAAAAAAAAAADvN2AQBr/original', 'goodsPrice': '4.00', 'sellStatus': 1, 'packageCount': 1, 'sellTime': '1970-01-01', 'goodsNo': '4317712/9999999', 'timePass': '1970-01-01 08:00:00', 'dealType': 0, 'goodsType': 1, 'goodsWantBuyCount': 0, 'count': 1, 'isPayBond': False, 'illegalCount': 0, 'isTransfer': True, 'isJintan': True, 'isCart': False, 'restitutionEndTime': '1970-01-01 08:00:00', 'supportPayType': [1, 2, 6], 'fancyNumberType': []}], 'auctionNum': 10}}
    return response

async def search_app_new(
    search_name: str = "",
    xm_auth: str = "",
    page_no: int = 1,
    page_size: int = 50
):
    """搜索XM藏品信息"""
    path = settings.XM_SEARCH_APP_NEW
    req_body = {
        "isShowArchive": True,
        "pageNum": page_no,
        "pageSize": page_size,
        "search": search_name
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    return response

async def get_my_wallet(xm_auth: str = ""):
    """查询XM我的钱包"""
    path = settings.XM_MY_WALLET
    req_body = {}
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    return response

async def prepay(goodsId: str, xm_auth: str = ""):
    """XM预支付"""
    path = settings.XM_PREPAY
    req_body = {
        "goodsId": goodsId
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {
    #   'code': 200, 
    #   'msg': '成功', 
    #   'data': {
    #       'hasAddress': True, 
    #       'sumAmount': 3.65, 
    #       'goodInfo': {
    #           'id': 45504034, 
    #           'name': '黑白双色锦鲤', 
    #           'amount': 3.65, 
    #           'img': ['https://mdn.alipayobjects.com/chain_myent/afts/img/XyJTRIk3s80AAAAAAAAAAAAADvN2AQBr/original'], 
    #           'goodsType': 1, 
    #           'platformName': '鲸探', 
    #           'platformId': None, 
    #           'count': None, 
    #           'goodsMinPrice': None, 
    #           'goodsDeliveryTime': None, 
    #           'restitutionEndTime': None, 
    #           'packageCount': 1
    #       }, 
    #       'phoneNum': '13632850648', 
    #       'name': '随你意', 
    #       'address': [
    #           {
    #               'id': 1596835, 
    #               'platformName': '鲸探', 
    #               'address': '66275399fef9aeb2d6553448d0ca0ccf663c28ae9bc8c1862a5cc180', 
    #               'platformId': '741', 
    #               'remark': ''
    #           }
    #       ], 
    #       'balance': 22.22, 
    #       'tranBalance': 0, 
    #       'bankMaxPay': 20000.0, 
    #       'sellerOpenTran': False, 
    #       'buyerOpenTran': False, 
    #       'sellerTransportOpenAccountStatus': 1, 
    #       'lockOrderTime': None, 
    #       'banTime': None, 
    #       'banReason': None, 
    #       'sellerOpenHfPay': True, 
    #       'earnestAmount': None, 
    #       'goodsAmountStatus': None, 
    #       'projectedRevenueAmount': None, 
    #       'isJTTransfer': True, 
    #       'isAuthTransfer': True, 
    #       'jtAddresseList': [
    #           {
    #               'id': 273976, 
    #               'avatar': 'https://mdn.alipayobjects.com/chain_myent/afts/img/jSRiQpcIXD4AAAAAAAAAAAAADvN2AQBr/original', 
    #               'nickname': '藏家_97****qcsz', 
    #               'expireTime': '2025-08-14 10:54:13', 
    #               'phone': None, 
    #               'isExpire': True
    #           }
    #       ], 
    #       'platformAuthAddressList': [
    #           {
    #               'id': 273976, 
    #               'avatar': 'https://mdn.alipayobjects.com/chain_myent/afts/img/jSRiQpcIXD4AAAAAAAAAAAAADvN2AQBr/original', 
    #               'nickname': '藏家_97****qcsz', 
    #               'expireTime': '2025-08-14 10:54:13', 
    #               'phone': None, 
    #               'isExpire': True
    #           }
    #       ]
    #   }
    #}
    return response

async def can_open_tran(xm_auth: str = ""):
    """XM是否可以开启交易"""
    path = settings.XM_CAN_OPEN_TRAN
    req_body = {}
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'canOpenTransaction': True}}
    return response

async def agreement_detailed(xm_auth: str = "", type: str = "user"):
    """XM协议详情"""
    path = settings.XM_AGREEMENT_DETAILED
    req_body = {
        "type": type
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'id': 20, 'agreementTitle': '用户协议', 'agreementContext': '平台协议'}}
    return response

async def check_amount(goodsId: str, amount: str, xm_auth: str = ""):
    """XM检查金额"""
    path = settings.XM_CHECK_AMOUNT
    req_body = {
        "goodsId": goodsId,
        "amount": amount
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'canPay': True, 'amount': 3.65}}
    return response

async def agreement_confirm(ids: List[int], xm_auth: str = ""):
    """XM协议确认"""
    path = settings.XM_AGREEMENT_SIGN
    req_body = {
        "ids": ids,
        "isSign": True
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': None}
    return response

async def check_pend_order(xm_auth: str = ""):
    """XM检查交易状态"""
    path = settings.XM_CHECK_PEND_ORDER
    req_body = {}
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': False}
    return response

async def verify_wallet_hash(addressId: str, goodsId: str, xm_auth: str = ""):
    """XM验证钱包哈希"""
    path = settings.XM_VERIFY_WALLET_HASH
    req_body = {
        "addressId": addressId,
        "goodsId": goodsId
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': None}
    return response

async def xm_unified_pay(addressId: str, goodsId: str, xm_auth: str = ""):
    """XM统一支付"""
    path = settings.XM_UNIFIED_PAY
    req_body = {
        "addressId": addressId,
        "goodsId": goodsId,
        "shortName": "YE",
        "devType": 2
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'timeStamp': None, 'nonceStr': None, 'packageStr': None, 'signType': None, 'appId': None, 'paySign': None, 'id': 33772401, 'payUrl': None, 'orderNo': '2025110519221695574877', 'isPay': None, 'isSuccess': None}}
    return response

async def create_order(
    goodsId: str, 
    goodsPrice: str, 
    isJTTransfer: bool = True, 
    xm_auth: str = ""
):
    """XM创建订单, 购买藏品"""
    # 1.调用prepay接口
    prepay_resp = await prepay(
        xm_auth=xm_auth,
        goodsId=goodsId
    )
    logger.info(f"prepay响应: {prepay_resp}")
    if prepay_resp["code"] != 200:
        return None
    # 获取鲸探秒转地址
    addressId = prepay_resp["data"]["jtAddresseList"][0]["id"]
    if not isJTTransfer:
        # 获取鲸探非秒转地址
        addressId = prepay_resp["data"]["address"][0]["id"]
    
    # 2.检查用户是否可购买
    can_tran_resp = await can_open_tran(xm_auth=xm_auth)
    logger.info(f"can_open_tran响应: {can_tran_resp}")
    if can_tran_resp["code"] != 200:
        return None
    if not can_tran_resp["data"]["canOpenTransaction"]:
        logger.error(f"用户不可购买: {can_tran_resp}")
        return None
    
    # 3.查询交易协议
    agreement_resp = await agreement_detailed(xm_auth=xm_auth)
    if agreement_resp["code"] != 200:
        logger.error(f"agreement_detailed失败: {agreement_resp}")
        return None
    # 获取协议ID
    agreementId = agreement_resp["data"]["id"]

    # 4.校验商品金额
    amount_check_resp = await check_amount(
        goodsId=goodsId,
        amount=goodsPrice,
        xm_auth=xm_auth
    )
    logger.info(f"check_amount响应: {amount_check_resp}")
    if amount_check_resp["code"] != 200:
        logger.error(f"check_amount失败: {amount_check_resp}")
        return None
    if not amount_check_resp["data"]["canPay"]:
        logger.error(f"商品金额校验失败: {amount_check_resp}")
        return None

    # 5. 确认协议
    confirm_resp = await agreement_confirm(
        ids=[agreementId],
        xm_auth=xm_auth
    )
    logger.info(f"agreement_confirm响应: {confirm_resp}")
    if confirm_resp["code"] != 200:
        return None
    
    # 6. 校验预定订单
    pend_order_resp = await check_pend_order(xm_auth=xm_auth)
    logger.info(f"check_pend_order响应: {pend_order_resp}")
    if pend_order_resp["code"] != 200:
        return None
    if pend_order_resp["data"]:
        logger.error(f"有未完成订单: {pend_order_resp}")
        return None
    
    # 7. 验证钱包哈希
    verify_resp = await verify_wallet_hash(
        addressId=addressId,
        goodsId=goodsId,
        xm_auth=xm_auth
    )
    logger.info(f"verify_wallet_hash响应: {verify_resp}")
    if verify_resp["code"] != 200:
        return None
    
    # 8. 统一支付
    pay_resp = await xm_unified_pay(
        addressId=addressId,
        goodsId=goodsId,
        xm_auth=xm_auth
    )
    # logger.info(f"xm_unified_pay响应: {pay_resp}")
    # code=40347 账户余额不足
    # if pay_resp["code"] != 200 or pay_resp["code"] != 40347:
    #     return None
    
    return pay_resp

async def archive_market(
    xm_auth: str = "",
    archiveId: str = ""
):
    """查询XM档案市场行情"""
    path = settings.XM_ARCHIVE_MARKET
    req_body = {
        "archiveId": archiveId,
        "timeType": 0
    }
    headers = {
        "authorization": xm_auth,
        "Content-Type": "application/json;charset=UTF-8"
    }
    url = f"{settings.XM_API_URL}{path}"
    response = await HttpClient.request(
        method="POST",
        url=url,
        headers=headers,
        json=req_body
    )
    # {'code': 200, 'msg': '成功', 'data': {'marketAmount': 60100000.0, 'marketAmountRate': -11.36, 'dealCount': 8455, 'dealCountRate': 79.08, 'minPrice': 6.01, 'minPriceRate': -11.36}}
    return response